<template>
  <h1>发微博页面</h1>
  <div style="width: 500px;margin: 0 auto">
    <el-input placeholder="微博正文" v-model="weibo.content"></el-input>
    <!--图片上传开始-->
    <el-upload
        v-model:file-list="fileList"
        action="http://localhost:8080/v1/upload"
        name="file"
        limit="9"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
    >
      <el-icon><Plus /></el-icon>
    </el-upload>

    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
    <!--图片上传结束-->
    <el-button type="primary" @click="post"
               style="width: 100px;margin:
               10px;font-weight: bold">发布
    </el-button>
  </div>
</template>

<script setup>
import {ref} from 'vue';
import router from "@/router";
import qs from "qs";
import axios from "axios";
import {ElMessage} from "element-plus";
import {Plus} from "@element-plus/icons-vue";

//图片上传开始
const fileList = ref([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
  //1.得到要删除的图片路径 uploadFile就是我们要删除的那个图片文件对象
  let imgUrl = uploadFile.response.data;
  //2.给后端发请求,删除图片
  axios.post('http://localhost:8080/v1/remove?imgUrl='+imgUrl)
      .then((res)=>{
        if (res.data.code==2002){
          ElMessage.success('删除成功!');
        }
      })
}
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}
//图片上传结束

const weibo =ref({content:""});
const post=()=>{
    let user = getUser();//改进的获取用户,调用全局的window方法
    if (user==null){//没有登录
      alert('请先登录!');
      router.push('/login');
      return;//结束方法
    }
    //判断是否上传图片
    if(fileList.value.length >0){//说明用户传图片了
      let imgUrls =[];//准备数组用来存多张图片路径
      for (let file of fileList.value){//遍历响应式数组
        //依次遍历得到每个文件的响应路径
        let imgUrl = file.response.data;
        //依次得到每张图片的路径,存入imgUrls数组中
        imgUrls.push(imgUrl);
      }
      weibo.value.imgUrls =imgUrls.toString();
    }
    weibo.value.userId = user.id;
    let data = qs.stringify(weibo.value);
    console.log(data);
    axios.post('http://localhost:8080/v1/weibos/add-new',data)
        .then((res)=>{
          if (res.data.code=2002){
            ElMessage.success('发布成功');
            router.push('/');
          }
        });
}
</script>


<style scoped>

</style>